#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include "wificonfig.h"

#define SW_PIN D1

const char* mqttServer = "192.168.1.162";
const char* topic_switch = "hqyjxa/switch/off";
const char* will_topic = "hqyjxa/switch/online";
WiFiClient wificlient;
PubSubClient client(wificlient);

void callback(char* topic, byte* payload, unsigned int length)
{
    Serial.println(topic);
    Serial.println(length);
    for (unsigned int i = 0; i < length; i++)
    {
        Serial.print((char)payload[i]);
    }
    Serial.println("");

    if (strcmp(topic, topic_switch) == 0)
    {
        //继电器低电平触发，写入1关闭，0开启
        digitalWrite(SW_PIN, payload[0] - '0');
    }
}

void reconnect() {
    //连接MQTT代理，客户端ID，用户名，密码，遗嘱主题，遗嘱QoS，遗嘱保留，遗嘱内容
    //连接成功后，将online主题（遗嘱）设置为1，表示设备上线，订阅者收到通知
    //连接非正常断开后，online内容会被代理设置为0，表示设备下线，订阅者收到通知。
    //https://pubsubclient.knolleary.net/api.html
    char clientID[16];
    sprintf(clientID, "hqyjxa-%08x", ESP.getChipId());
    if (client.connect(clientID, NULL, NULL, will_topic, 1, 1, "0")) {
        Serial.print(clientID);
        Serial.println(" connected");
        client.subscribe(topic_switch, 1);
        client.publish(will_topic, "1", true);
        digitalWrite(LED_BUILTIN, LOW); //LED On
    } else {
        Serial.print("connect failed ");
        Serial.print(client.state());
        Serial.println(", try again in 1 second");
        digitalWrite(LED_BUILTIN, HIGH); //LED Off
        delay(1000);
    }
}

void setup() {
    Serial.begin(115200);
    autoConfig();

    client.setServer(mqttServer, 1883);
    client.setCallback(callback);
    pinMode(SW_PIN, OUTPUT);
    digitalWrite(SW_PIN, HIGH);//默认设置为关闭
}

void loop() {
    if (!client.connected()) {
        reconnect();
    }
    client.loop();
}
